import {query} from '../services/essence'
import {ListView} from 'antd-mobile'

export default{
    
    namespace: "essence",

    state:{
        dataList: [],
        page: 1,
        size: 10,
        refreshing: false,
        dataSource: new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1.id !== row2.id
        }),
        loading: false,
    },

    subscriptions:{
        setup({dispatch, history}){
        },
    },

    effects:{
        *refresh({payload}, {select, call, put}){

            yield put({type: 'beginRefresh'})

            const page = yield select(({essence})=>essence.page)
            const size = yield select(({essence})=>essence.size)

            const {data} = yield call(query, {page, size})

            if(data){
                yield put({type: 'endRefresh'})

                yield put({
                    type: 'refreshSuccess',
                    payload: {
                        list: data.feed.entry
                    }
                })
            }
        },
        *query({payload}, {select, call, put}){
            yield put({type: 'beginLoading'})

            const page = yield select(({essence})=>essence.page)
            const size = yield select(({essence})=>essence.size)

            const {data} = yield call(query, {page, size})

            if(data){

                yield put({
                    type: 'querySuccess',
                    payload: {
                        list: data.feed.entry
                    }
                })

                yield put({type: 'endLoading'})
            }
        }
    },

    reducers:{
        refreshSuccess(state, action){

            state.dataList = action.payload.list

            const newDataSource = state.dataSource.cloneWithRows(state.dataList)

            return {...state, dataSource: newDataSource}
        },
        querySuccess(state, action){
            action.payload.list.forEach((value)=>{ 
                state.dataList.push(value)
            })

            const newDataSource = state.dataSource.cloneWithRows(state.dataList) 

            return {...state, dataSource: newDataSource}
        },
        beginRefresh(state){

            return {...state, refreshing: true, page : 1}
        },
        endRefresh(state){
            state.page = 2

            return {...state, refreshing: false}
        },
        beginLoading(state){
            state.loading = true

            return {...state}
        },
        endLoading(state){
            state.loading = false
            state.page = state.page + 1
            
            return {...state}
        }
    },
}